﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WuxiWTO.Mapping;
using WutiWTO.Common;
using System.Data.Linq;

namespace WuxiWTO.Web.backend
{
    public partial class articleEdit : BasePage
    {
        int cid = 0;
        /// <summary>
        /// 更新模式
        /// </summary>
        protected bool UpdateMode
        {
            get
            {
                if (!string.IsNullOrEmpty(Request.QueryString["id"]))
                {
                    cid = int.Parse(Request.QueryString["id"]);
                    ViewState["cid"] = int.Parse(Request.QueryString["id"]);
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }

        WTODataContext ctx = new WTODataContext();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //BindGrid();
                BuildTheParentCategory();
                if (UpdateMode)
                {
                    GetInfo();
                }
                else
                {
                    panAttachment.Visible = false;
                }
            }
        }

        private void GetInfo()
        {
            article cat = ctx.articles.SingleOrDefault(p => p.article_id == cid);
            if (cat != null)
            {
                this.ddlParentCategory.Items.FindByValue(cat.parent_category_id.ToString()).Selected = true;
                ddlParentCategory_SelectedIndexChanged(null, null);
                if (cat.category_id != null)
                {
                    this.ddlCategory.Items.FindByValue(cat.category_id.ToString()).Selected = true;
                }
                this.ddlParentCategory.Enabled = false;
                this.ddlCategory.Enabled = false;
                this.txtTitle.Text = cat.article_title;
                this.txtAuthor.Text = cat.author;
                this.txtSource.Text = cat.source;
                this.editor1.Text = cat.article_content;
                if (!string.IsNullOrEmpty(cat.attachment_path))
                {
                    panAttachment.Visible = true;
                    ViewState["file_path"] = cat.attachment_path;
                    this.btnDownloadFile.Text = cat.attachment_path.Substring(cat.attachment_path.LastIndexOf("/") + 1, cat.attachment_path.Length - cat.attachment_path.LastIndexOf("/") - 1);
                }
                else
                {
                    panAttachment.Visible = false;
                }
            }
            else
            {
                ClientScript.RegisterStartupScript(this.GetType(), "fa", "alert('参数传递失败');", true);
            }
        }

        protected void btnDeleteFile_Click(object sender, ImageClickEventArgs e)
        {
            if (ViewState["file_path"] != null)
            {
                string file_path = Server.MapPath("..") + ViewState["file_path"].ToString();
                int tempID = 0;
                if (System.IO.File.Exists(file_path))
                {
                    System.IO.File.Delete(file_path);
                }
                if (ViewState["cid"] != null)
                {
                    tempID = (int)ViewState["cid"];
                }
                article cat = ctx.articles.SingleOrDefault(p => p.article_id == tempID);
                if (cat != null)
                {
                    cat.attachment_path = "";
                    ctx.SubmitChanges();
                }
                this.panAttachment.Visible = false;
            }
        }

        protected void btnDownloadFile_Click(object sender, EventArgs e)
        {
            if (ViewState["file_path"] != null)
            {
                string fileName = ViewState["file_path"].ToString();//客户端保存的文件名
                fileName = fileName.Substring(fileName.LastIndexOf("/") + 1, fileName.Length - fileName.LastIndexOf("/") - 1);
                string filePath = Server.MapPath("..") + ViewState["file_path"].ToString();//路径

                System.IO.FileInfo fileInfo = new System.IO.FileInfo(filePath);
                if (fileInfo.Exists)
                {
                    Response.Clear();
                    Response.ClearContent();
                    Response.ClearHeaders();
                    Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
                    Response.AddHeader("Content-Length", fileInfo.Length.ToString());
                    Response.AddHeader("Content-Transfer-Encoding", "binary");
                    Response.ContentType = "application/octet-stream";
                    Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
                    Response.WriteFile(fileInfo.FullName);
                    Response.Flush();
                    Response.End();
                }
                else
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "fa", "alert('该文件不存在');", true);
                    return;
                }
            }

        }

        private void BuildTheParentCategory()
        {
            this.ddlParentCategory.Items.Clear();
            var parent = ctx.categories.Where(p => p.art_parent_kind == 0).ToList();
            foreach (category cat in parent)
            {
                this.ddlParentCategory.Items.Add(new ListItem(cat.art_kind_name, cat.art_kind_id.ToString()));
            }
            this.ddlParentCategory.Items.Insert(0, new ListItem("--请选择--", ""));
        }

        protected void ddlParentCategory_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.ddlCategory.Items.Clear();
            int pid=Utility.ConvertIntFromString(this.ddlParentCategory.SelectedItem.Value);
            var cat = from c in ctx.categories where c.art_parent_kind == pid select c;
            List<category> cates =  cat.ToList<category>();
            foreach (category item in cates)
            {
                ListItem dropItem = new ListItem(item.art_kind_name, item.art_kind_id.ToString());
                this.ddlCategory.Items.Add(dropItem);
            }
            this.ddlCategory.Items.Insert(0, new ListItem("--请选择--", "-1"));
        }

        protected void btnOK_Click(object sender, EventArgs e)
        {
            //新建模式
            if (!UpdateMode)
            {
                int pid = int.Parse(this.ddlParentCategory.SelectedValue);
                int categoryID = int.Parse(this.ddlCategory.SelectedValue);

                category kind;
                if (categoryID == -1)
                {
                    kind = ctx.categories.SingleOrDefault(p => p.art_kind_id == pid);

                }
                else
                {
                    kind = ctx.categories.SingleOrDefault(p => p.art_kind_id == categoryID);
                }
                if (kind.single_page.Value)
                {
                    var artList = ctx.articles.Where(p => p.parent_category_id == pid && p.category_id == categoryID).ToList();
                    if (artList.Count >= 1)
                    {
                        ClientScript.RegisterStartupScript(this.GetType(), "overflowart", "alert('该分类属于单一页面分类，并且下面已经存在一篇文章，不能添加！请更换其他分类！');", true);
                        return;
                    }
                }
            }

            string fileDBPath = "";
            //如果选择上传文件
            if (this.upload1.HasFile)
            {
                fileDBPath = "attachment//" + upload1.FileName;
                upload1.SaveAs(Server.MapPath("~//attachment//") + upload1.FileName);
            }
            //上传新闻标题图片
            string titleImage = "images/companyBg.jpg";
            if (this.fileUpload.HasFile)
            {
                if (".jpg.jpeg.gif.png".Contains(System.IO.Path.GetExtension(fileUpload.FileName).ToLower()))
                {
                    string filePath = Server.MapPath(@"~/uploads/news/");
                    string fileName = fileUpload.FileName;
                    string savePath = filePath + fileName;
                    if (!System.IO.Directory.Exists(filePath))
                    {
                        System.IO.DirectoryInfo path = System.IO.Directory.CreateDirectory(filePath);
                    }
                    fileUpload.SaveAs(savePath);

                    Utility.MakeThumbnail(savePath, filePath + "thumb_" + fileName, Utility.ThumbType.CUT, 90, 70);
                    titleImage = "uploads/news/" + "thumb_" + fileName;
                }
                else
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "fa1", "alert('上传图片格式错误,请上传后缀名为:.jpg/.jpeg/.gif/.png格式的图片');", true);
                    return;
                }
            }


            article art;
            if (UpdateMode)
            {
                art = ctx.articles.SingleOrDefault(p => p.article_id == cid);
                if (art == null)
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "fa", "alert('参数传递失败');", true);
                    return;
                }
            }
            else
                art = new article();
            art.article_title = this.txtTitle.Text.Trim();
            art.author = this.txtAuthor.Text.Trim();
            art.source = this.txtSource.Text.Trim();
            art.parent_category_id = Utility.ConvertIntFromString(this.ddlParentCategory.SelectedItem.Value);
            if (this.ddlCategory.SelectedItem.Value != "")
            {
                art.category_id = Utility.ConvertIntFromString(this.ddlCategory.SelectedItem.Value);
            }
            art.article_content = this.editor1.Text;
            art.update_date = DateTime.Now;
            art.attachment_path = fileDBPath;
            art.update_user = Session["login_name"] == null ? "" : Session["login_name"].ToString();
            art.article_title_image = titleImage;
            if (!UpdateMode)
            {
                art.created_date = DateTime.Now;
                art.read_count = 0;
                art.created_user = Session["login_name"] == null ? "" : Session["login_name"].ToString();
                ctx.articles.InsertOnSubmit(art);
            }
            ctx.SubmitChanges();
            Response.Redirect("articleList.aspx");
        }
    }
}